import { defineStore } from 'pinia'
import { ref } from 'vue'

export const usePermissionStore = defineStore('permission', () => {
  const permissions = ref([])

  /**
   * 检查是否具有指定权限
   * @param {Array} requiredPermissions - 需要检查的权限数组
   * @returns {Boolean} - 是否具有权限
   */
  const hasPermission = (requiredPermissions) => {
    console.log('检查权限:', { required: requiredPermissions, current: permissions.value })
    if (!requiredPermissions || requiredPermissions.length === 0) {
      console.log('无需权限检查，默认通过')
      return true
    }
    // 如果用户是超级管理员，直接返回true
    if (permissions.value.includes('admin')) {
      console.log('超级管理员权限，自动通过')
      return true
    }
    const result = permissions.value.some(permission => requiredPermissions.includes(permission))
    console.log('权限检查结果:', result)
    return result
  }

  const filterAsyncRoutes = (routes) => {
    console.log('开始过滤异步路由:', routes)
    const res = []

    routes.forEach(route => {
      const tmp = { ...route }
      console.log('检查路由权限:', { route: tmp.path, permissions: tmp.meta?.permissions })
      if (hasPermission(tmp.meta?.permissions)) {
        if (tmp.children) {
          console.log('处理子路由:', tmp.path)
          tmp.children = filterAsyncRoutes(tmp.children)
        }
        res.push(tmp)
      }
    })

    console.log('过滤后的路由:', res)
    return res
  }

  const setPermissions = (userPermissions) => {
    console.log('设置用户权限:', userPermissions)
    permissions.value = userPermissions
  }

  return {
    permissions,
    hasPermission,
    filterAsyncRoutes,
    setPermissions
  }
})